import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 用户信息接口
/**
 * @typedef {Object} UserProfile
 * @property {string} id - 用户ID
 * @property {string} username - 用户名
 * @property {string} avatar - 头像URL
 * @property {string} email - 邮箱
 */

/**
 * @typedef {Object} LoginForm
 * @property {string} username - 用户名
 * @property {string} password - 密码
 */

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref((() => {
    const stored = localStorage.getItem('userInfo')
    if (!stored) return {}
    try {
      return JSON.parse(stored)
    } catch (e) {
      console.error('Failed to parse stored user info:', e)
      return {}
    }
  })())
  const preferences = ref((() => {
    const defaultPreferences = {
      theme: 'light',
      themeColor: '#1989fa',
      themeImage: ''
    }
    
    const stored = localStorage.getItem('preferences')
    if (!stored) return defaultPreferences
    
    try {
      return JSON.parse(stored) || defaultPreferences
    } catch (e) {
      console.error('Failed to parse stored preferences:', e)
      return defaultPreferences
    }
  })())
  
  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const username = computed(() => userInfo.value.username || '游客')
  const userAvatar = computed(() => {
    return userInfo.value.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
  })
  
  // 方法
  /**
   * 用户登录
   * @param {Object} credentials - 登录凭证
   * @returns {Promise} 登录结果
   */
  const login = async (credentials) => {
    try {
      // 实际的API调用
      const response = await fetch('http://localhost:8282/api/user/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(credentials)
      });
      const data = await response.json();
  
      if (data.code === 200) {
        // 保存用户信息
        token.value = data.token;
        userInfo.value = data.userInfo;
  
        // 持久化存储
        localStorage.setItem('token', token.value);
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
  
        return { success: true };
      } else {
        return { success: false, message: data.message || '登录失败，请稍后再试' };
      }
    } catch (error) {
      console.error('登录失败:', error);
      return { success: false, message: error.message || '登录失败，请稍后再试' };
    }
  }
  
  
  /**
   * 用户登出
   */
  const logout = () => {
    // 清除用户信息
    token.value = ''
    userInfo.value = {}
    
    // 清除本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }
  
  /**
   * 更新用户信息
   * @param {Object} data - 用户信息
   */
  const updateUserInfo = (data) => {
    userInfo.value = { ...userInfo.value, ...data }
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }
  
  /**
   * 更新主题
   * @param {string} theme - 主题名称 ('light' | 'dark' | 'auto')
   */
  const updateTheme = (theme) => {
    preferences.value.theme = theme
    savePreferences()
    
    // 更新文档根元素的data-theme属性
    document.documentElement.setAttribute('data-theme', theme)
  }
  
  /**
   * 更新主题颜色
   * @param {string} color - 颜色值，如 #1989fa
   */
  const updateThemeColor = (color) => {
    preferences.value.themeColor = color
    savePreferences()
    
    // 设置根元素CSS变量
    document.documentElement.style.setProperty('--primary-color', color)
    
    // 转换颜色为RGB格式
    const r = parseInt(color.slice(1, 3), 16)
    const g = parseInt(color.slice(3, 5), 16)
    const b = parseInt(color.slice(5, 7), 16)
    document.documentElement.style.setProperty('--primary-color-rgb', `${r}, ${g}, ${b}`)
  }
  
  /**
   * 更新主题背景图片
   * @param {string} imageUrl - 图片URL
   */
  const updateThemeImage = (imageUrl) => {
    preferences.value.themeImage = imageUrl
    savePreferences()
    
    if (imageUrl) {
      // 设置背景图片
      document.body.style.backgroundImage = `url(${imageUrl})`
      document.body.style.backgroundSize = 'cover'
      document.body.style.backgroundAttachment = 'fixed'
    } else {
      // 移除背景图片
      document.body.style.backgroundImage = 'none'
    }
  }
  
  /**
   * 更新头像
   * @param {string} avatarUrl - 头像URL
   */
  const updateAvatar = (avatarUrl) => {
    if (!userInfo.value) {
      userInfo.value = {}
    }
    userInfo.value.avatar = avatarUrl
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }
  
  /**
   * 保存偏好设置
   */
  const savePreferences = () => {
    localStorage.setItem('preferences', JSON.stringify(preferences.value))
  }
  
  /**
   * 初始化主题
   */
  const initTheme = () => {
    const { theme, themeColor, themeImage } = preferences.value
    
    // 设置主题模式
    if (theme) {
      document.documentElement.setAttribute('data-theme', theme)
    }
    
    // 设置主题颜色
    if (themeColor) {
      updateThemeColor(themeColor)
    }
    
    // 设置背景图片
    if (themeImage) {
      updateThemeImage(themeImage)
    }
  }
  
  // 初始化主题
  initTheme()
  
  return {
    // 状态
    token,
    userInfo,
    preferences,
    
    // 计算属性
    isLoggedIn,
    username,
    userAvatar,
    
    // 方法
    login,
    logout,
    updateUserInfo,
    updateTheme,
    updateThemeColor,
    updateThemeImage,
    updateAvatar,
    savePreferences,
    initTheme
  }
})